/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.stdlib.text.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.Formatting;
import axil.api.Persona;
import axil.api.error.AxilException;
import axil.framework.collection.SingletonIterator;
import axil.framework.type.Added;
import axil.framework.type.Subtracted;
import axil.stdlib.core.type.Nil;
import axil.stdlib.numbers.type.Int;

import java.util.Iterator;

import static axil.framework.Functions.*;


/**
 * An Axil representation of a character as an object.
 */
public class Char extends Text implements Added, Subtracted
{
	public static final AxilType type = Char_Type.object;
	private static final int SIZE = 128;
	private static final Char[] CACHE = new Char[SIZE];
	static {
		for (int i = 0; i < SIZE; i++) {
			CACHE[i] = new Char((char)i);
		}
	}

	private char ch;


	public Char(char ch) {
		this.ch = ch;
	}


	public static Char from(char ch) {
		return ch < SIZE ? CACHE[ch] : new Char(ch);
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Returns a hash code value for the object. All Axil values must provide a
	 * meaningful implementation of this function to enable themselves to be
	 * placed in a map or set.
	 */
	protected int hash() {
		return ch;
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
        // Char is only equal if there is only one char, and it matches.
		if (object instanceof Text) {
			Text v = (Text)object;
			if (v.size() == 1) {
				return v.ch(0) == ch;
			} else {
                return false;
            }
		}
        // "nil" comparison; always false.
        if (object == Nil.object) {
            return false;
        }
        String otherString = object.toString();
        if (otherString.length() == 1) {
            return otherString.charAt(0) == ch;
        }
        return false;
    }


	/**
	 * Compares this object with the specified object for order. If the given
	 * object is not a suitable type for comparison, a ClassCastException may
	 * be thrown.
	 *
	 * @param object
	 * 	The object to compare against. The given object cannot be null but may
	 * 	be any Axil object.
	 *
	 * @return
	 * 	Returns a negative integer, zero, or a positive integer as this object
	 * 	is less than, equal to, or greater than the specified object.
	 */
	public int comparedTo(AxilObject object) {
        if (object instanceof Text) {
            Text v = (Text)object;
            if (v.size() == 1) {
                return ch - ((Text)object).ch(0);
            } else {
                int firstCompare = ch - v.first().ch;
                if (0 == firstCompare) {
                    // The other has the same first char, but more than one character; making this char smaller
                    return (0 - ((Text)object).size());
                }
                return firstCompare;
            }
        }
        // "nil" comparison; always return 1 (nil less than everything).
        if (object == Nil.object) {
            return 1;
        }
        String otherString = object.toString();
        int diff = ch - (otherString.charAt(0));
        if ((diff == 0) && (otherString.length() > 1))
        {
            // The other has the same first char, but more than one character; making this char smaller
            return (0 - otherString.length());
        }
        return diff;
    }


	/**
	 * Get the size of this text object. The size returned is always greater
	 * than or equal to zero.
	 */
	public int size() {
		return 1;
	}


	/**
	 * Get the character at the given index (from zero). If the index is outside
	 * of the range of the object, then an exception is thrown.
	 */
	public char ch(int index) {
		if (index != 0) {
			throw abort("That makes no sense.");
		}
		return ch;
	}


	/**
	 * Get the element at the given index, where the first object is at index
	 * zero. If there is no element at that position, then a null is returned.
	 */
	public Char at(int index) {
		return index == 0 ? this : null;
	}


	/**
	 * Get the first element from this sequential collection, or return null
	 * if this collection is empty.
	 */
	public Char first() {
		return this;
	}


	/**
	 * Get the last element from this sequential collection, or return null if
	 * this collection is empty.
	 */
	public Char last() {
		return this;
	}


	/**
	 * Add the given value to this value, returning a new object. The given
	 * value is never null or nil. The value may be a numeric type of any other
	 * type of object that can sensibly implement the Added interface.
	 */
	public AxilObject add(AxilObject object) {
		if (object instanceof Str) {
			return Str.from(this.toString() + object.toString());
		}
		if (object instanceof Int) {
			return Char.from((char)((int)ch + ((Int)object).value()));
		}
		if (object instanceof Char) {
			return Str.from(this.toString() + object.toString());
		}
		throw error(axil(), "invalid-operand",
			 nv("operator", "-"), nv("type", object.type()));
	}


	/**
	 * Subtract the given object from this object. The given value is never
	 * null or nil. The value may be a numeric type of any other type of object
	 * that can sensibly implement the Subtracted interface.
	 */
	public AxilObject subtract(AxilObject object) {
		if (object instanceof Int) {
			return Char.from((char)((int)ch - ((Int)object).value()));
		}
		throw error(axil(), "invalid-operand",
			 nv("operator", "-"), nv("type", object.type()));
	}


	/**
	 * Returns an iterator over a set of elements of this type.
	 */
	public Iterator<Char> iterator() {
		return new SingletonIterator(this);
	}


	/**
	 * Format this object in a locale-friendly manner. The string returned is
	 * a localized representation of this object using the locale and timezone
	 * associated with this persona. The formatting given is never null and
	 * matches formatting suitable for this type.
	 */
	public String format(Persona persona, Formatting formatting) {
		return (ch == 0) ? "" : Character.toString(ch);
	}


	/**
	 * Tell if this object, represents a true or false value. In general, true
	 * is returned for any object that is not equivalent to nil, is a number
	 * greater than zero, or is the boolean true value.
	 */
	public boolean bool() {
		return ch > 0;
	}


	/**
	 * Get the native Java value in its most natural form. This is usd by the
	 * low-level inner workings of Axil.
	 */
	public char value() {
		return ch;
	}


	/**
	 * Return the host application (or built-in Java) object that most closely
	 * matches this value object. Return returned value is never null unless
	 * this value object represents the special 'nil' object.
	 */
	public Object intrinsic() {
		return ch;
	}


	/**
	 * Coerce this object into an instance of the given type. If this object
	 * cannot be meaningfully represented as an instance of that type, then an
	 * exception is thrown.
	 *
	 * @param type
	 * 	The type to be coerced to. The object given cannot be null.
	 *
	 * @return
	 * 	Returns an instance of the given type. If this object is nil, then nil
	 * 	is returned.
	 */
	public AxilObject coerce(AxilType type) throws AxilException {
		if (type == type()) {
			return this;
		}
		if (type == Int.type) {
			return Int.from((int)ch);
		}
		throw error(axil(), "cannot-coerce-object",
		            nv("from", type()), nv("to", type));
	}

    /**
     * Return a string representation of this object. The string returned is
     * never null.
     */
    public String toString() {
        return String.valueOf(ch);
    }
}
